package org.npu.filter;

import org.npu.entity.Admin;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AdminFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //1.调用请求对象读取请求包中请求行中的URI，了解用户访问的资源文件是谁
        String uri = req.getRequestURI();//[/网站名/资源文件名  /bigWeb/adminpage]

        if (uri.contains("adminpage") || uri.contains("adminop")){
            //需要拦截的界面
            Admin admin = (Admin) req.getSession().getAttribute("admin");
            if (admin == null){
                //该管理员没登陆，拦截
                req.getRequestDispatcher("/admin.html").forward(req,resp);
                //System.out.println("=======管理员拦截=========");
            }
        }

        //默认和其余放行
        filterChain.doFilter(req,resp);

    }

    @Override
    public void destroy() {

    }
}
